<template>
  <div class="container">
    <el-card>
      <el-row class="header"> {{ isEdit ? "试题修改" : "试题录入" }} </el-row>
      <el-divider class="line1"></el-divider>
      <el-form
        ref="addQuestionFormRef"
        :model="addQuestionForm"
        label-width="112px"
        :rules="addQuestionFormRules"
      >
        <el-row class="inputWith">
          <el-form-item label="学科 : " prop="subjectID">
            <el-select
              v-model="addQuestionForm.subjectID"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in subjectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录 : " prop="catalogID">
            <el-select
              v-model="addQuestionForm.catalogID"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in directoryList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业 : " prop="enterpriseID">
            <el-select
              v-model="addQuestionForm.enterpriseID"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in enterpriseIDList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-row type="flex">
            <el-col :span="15">
              <el-form-item label="城市 : " prop="province">
                <el-select
                  v-model="addQuestionForm.province"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in provinceList"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="9" class="citys">
              <el-form-item prop="city" class="city">
                <el-select
                  v-model="addQuestionForm.city"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in cityList"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="方向 : " prop="direction">
            <el-select
              v-model="addQuestionForm.direction"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in directionList"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型 : " prop="questionType">
            <el-radio-group v-model="addQuestionForm.questionType">
              <el-radio
                :label="item.value + ''"
                v-for="item in questionTypeList"
                :key="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度 : " prop="difficulty">
            <el-radio-group v-model="addQuestionForm.difficulty">
              <el-radio
                :label="item.value + ''"
                v-for="item in difficultyList"
                :key="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-form-item label="题干 : " prop="question">
          <quill-editor
            class="quill-editor"
            ref="myQuillEditor"
            v-model="addQuestionForm.question"
            :options="editorOption"
          />
        </el-form-item>
        <!-- 选项区域 -->
        <div
          class="radio inputWith item-margin-top"
          v-if="addQuestionForm.questionType === '1'"
        >
          <el-form-item label="选项 : ">
            <el-row
              type="flex"
              class="option-row"
              v-for="(item, index) in addQuestionForm.options"
              :key="index"
            >
              <el-radio
                class="option-radio"
                v-model="radioAnswers"
                :label="item.code"
                @change="changeRadioAnswer"
              >
                {{ item.code + " : " }}
              </el-radio>
              <el-input
                clearable
                v-model="item.title"
                class="option-title"
              ></el-input>
              <el-upload
                class="upload-demo"
                drag
                :limit="1"
                action="https://jsonplaceholder.typicode.com/posts/"
              >
                <div class="el-upload__text">上传图片</div>
                <i
                  class="el-icon-circle-close"
                  @click.stop="deleteRadioOption(item)"
                ></i>
              </el-upload>
            </el-row>
            <el-button
              type="danger"
              class="add-option"
              @click="addOption"
              size="mini"
              :disabled="
                addQuestionForm.questionType === '1' &&
                addQuestionForm.options.length >= 4
              "
              >+增加答案和选项11</el-button
            >
          </el-form-item>
        </div>
        <!-- 多选区域 -->
        <div
          class="checkbox inputWith"
          v-if="addQuestionForm.questionType === '2'"
        >
          <el-form-item label="选项 : ">
            <el-row
              type="flex"
              class="option-row"
              v-for="(item, index) in addQuestionForm.options"
              :key="index"
            >
              <el-checkbox
                class="option-checkbox"
                v-model="checkboxAnswers"
                :label="item.code"
                @change="changeCheckboxAnswer"
              >
                {{ item.code + " :  " }}
              </el-checkbox>
              <el-input
                clearable
                v-model="item.title"
                class="option-title"
              ></el-input>
              <el-upload
                class="upload-demo"
                drag
                :limit="1"
                action="https://jsonplaceholder.typicode.com/posts/"
              >
                <div class="el-upload__text">上传图片</div>
                <i
                  class="el-icon-circle-close"
                  @click.stop="deleteCheckboxOption(item)"
                ></i>
              </el-upload>
            </el-row>
            <el-button
              type="danger"
              class="add-option"
              @click="addOption"
              size="mini"
              >+增加答案和选项</el-button
            >
          </el-form-item>
        </div>
        <el-form-item label="解析视频 : " class="inputWith" prop="videoURL">
          <el-input v-model="addQuestionForm.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析 : " prop="answer">
          <quill-editor
            class="quill-editor"
            ref="myQuillEditor"
            v-model="addQuestionForm.answer"
            :options="editorOption"
          />
        </el-form-item>
        <el-form-item
          label="题目备注 : "
          class="inputWith item-margin-top"
          prop="remarks"
        >
          <el-input
            v-model="addQuestionForm.remarks"
            :rows="3"
            type="textarea"
            resize="none"
          ></el-input>
        </el-form-item>
        <el-form-item label="试题标签 : " class="inputWith" prop="tags">
          <el-select
            v-model="addQuestionForm.tags"
            placeholder="请选择试题标签"
            multiple
          >
            <el-option
              v-for="item in tagList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="inputWith">
          <el-button type="primary" @click="OnAddQuestion" v-if="!isEdit"
            >确认提交</el-button
          >
          <el-button type="success" @click="OnEditQuestion" v-if="isEdit"
            >确认修改</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 学科接口
import { simple as getSubjectsList } from '@/api/hmmm/subjects.js'
// 目录接口
import { simple as getDirectoryList } from '@/api/hmmm/directorys.js'
// 标签接口
import { simple as getTags } from '@/api/hmmm/tags.js'
// 企业接口
import { list as getEnterpriseList } from '@/api/hmmm/companys.js'
// 引入获取城市数据方法数据
import { provinces, citys } from '@/api/hmmm/citys.js'
// 引入数据对比
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import { add, detail, update } from '@/api/hmmm/questions.js'
export default {
  name: 'QuestionsNew',
  data () {
    return {
      addQuestionForm: {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: null, // 城市
        city: null, // 地区
        direction: null, // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: null, // 题干
        options: [
          {
            code: 'A', // 代码
            title: '', // 标签
            img: '', // 图片
            isRight: false // 是否是正确答案
          },
          {
            code: 'B', // 代码
            title: '', // 标签
            img: '', // 图片
            isRight: false // 是否是正确答案
          },
          {
            code: 'C', // 代码
            title: '', // 标签
            img: '', // 图片
            isRight: false // 是否是正确答案
          },
          {
            code: 'D', // 代码
            title: '', // 标签
            img: '', // 图片
            isRight: false // 是否是正确答案
          }
        ],
        videoURL: '', // 视频解析
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: [] // 试题标签
      },
      addQuestionFormRules: {
        // 表单验证规则
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }], // 学科
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }], // 目录
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ], // 企业
        province: [{ required: true, message: '请选择城市', trigger: 'blur' }], // 城市
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }], // 地区
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }], // 方向
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ], // 题型
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ], // 难度
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }], // 题干
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ], // 答案解析
        videoURL: [
          { required: true, message: '请输入视频地址', trigger: 'blur' }
        ], // 视频地址
        remarks: [
          { required: true, message: '请输入题目备注', trigger: 'blur' }
        ], //
        tags: [
          { required: true, message: '至少选择一个试题标签', trigger: 'blur' }
        ] // 试题标签
      },
      radioAnswers: null, // 单选正确答案
      checkboxAnswers: [], // 多选正确答案
      subjectList: [], // 学科列表数据
      directoryList: [], // 目录列表
      enterpriseIDList: [], // 企业列表
      provinceList: [], // 城市列表
      cityList: [], // 地区列表
      directionList: [], // 方向列表
      questionTypeList: [], // 问题类型列表
      difficultyList: [], // 难度列表
      tagList: [], // 试题标签列表
      oneEdit: false, // 当为修改时,用于阻止学科对应侦听器
      oneEdit1: false, // 当为修改时,用于阻止城市对应侦听器
      oneEdit2: false, // 当为修改时,用于阻止题型对应侦听器
      // 富文本配置
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            ['blockquote'], // 引用，代码块
            ['code-block', 'image', 'link']
          ]
        }
      }
    }
  },
  async created () {
    // 获取学科列表
    const { data: subjectList } = await getSubjectsList()
    this.subjectList = subjectList
    // 获取企业列表
    const {
      data: { items }
    } = await getEnterpriseList({ pagesize: 100 })
    this.enterpriseIDList = items
    // 获取城市列表
    this.provinceList = provinces()
    // 获取方向列表
    this.directionList = direction
    // 获取问题类型列表
    this.questionTypeList = questionType
    // 获取难度列表
    this.difficultyList = difficulty
    // 当是修改时
    if (this.$route.query.id) {
      const questionDetail = await detail({ id: this.$route.query.id })
      this.addQuestionForm = questionDetail.data
      this.addQuestionForm.tags = this.addQuestionForm.tags.split(',')
      // 如果是单选,就筛选单选选中项
      if (this.addQuestionForm.questionType === '1') {
        this.addQuestionForm.options.some((t) => {
          if (t.isRight) {
            this.radioAnswers = t.code
            return true
          }
        })
      }
      // 如果是单选,就筛选单选选中项
      if (this.addQuestionForm.questionType === '2') {
        this.addQuestionForm.options.forEach((t) => {
          if (t.isRight) {
            this.checkboxAnswers.push(t.code)
          }
        })
      }
    }
    // 直接在data中调用this.$options.data()会报错
    this.oneEdit = !this.$route.query.id
    this.oneEdit1 = !this.$route.query.id
    this.oneEdit2 = !this.$route.query.id
  },
  methods: {
    // 增加答案和选项
    addOption () {
      let last = this.addQuestionForm.options[
        this.addQuestionForm.options.length - 1
      ]
      // 数组没有对象的情况下
      if (last) {
        last = last.code
      } else {
        last = '@' // 因为@是A,ascll码的数字前一位
      }
      const code = String.fromCharCode(last.charCodeAt() + 1)
      this.addQuestionForm.options.push({
        code, // 代码
        title: '', // 标签
        img: '', // 图片
        isRight: false // 是否是正确答案
      })
    },
    // 当单选按钮发生变化时
    changeRadioAnswer () {
      // 干掉所有人
      this.addQuestionForm.options.forEach((t) => {
        t.isRight = false
      })
      // 留下我自己
      this.addQuestionForm.options[
        this.radioAnswers.charCodeAt() - 65
      ].isRight = true
    },
    // 删除单选选项
    deleteRadioOption (item) {
      // 记录删除元素是否已找到
      let flag = false
      // 记录删除元素在数组中的索引
      let num = null
      this.addQuestionForm.options.forEach((t, i) => {
        // 判断是不是删除元素后面的元素，且删除的元素不是数组的最后一个
        if (flag && num < this.addQuestionForm.options.length - 1) {
          t.code = String.fromCharCode(t.code.charCodeAt() - 1)
        }
        // 当找到元素后flag变为true，且记录删除元素的索引
        if (t === item) {
          flag = true
          num = i
          // 如果删除的是选中答案,则清空答案的值(BUG修复)
          if (item.code === this.radioAnswers) {
            this.radioAnswers = null
          }
          // 如果删除的是选中答案前面的,则让答案字母降1(bug修复)
          if (item.code < this.radioAnswers) {
            this.radioAnswers = String.fromCharCode(
              this.radioAnswers.charCodeAt() - 1
            )
          }
        }
        // 由于删除元素会导致遍历减少问题，所以放在最后一个元素删除
        if (i === this.addQuestionForm.options.length - 1) {
          this.addQuestionForm.options.splice(num, 1)
        }
      })
    },
    // 当多选按钮发生变化时
    changeCheckboxAnswer () {
      // 多选发生变化,调整发送请求的数据
      this.addQuestionForm.options.forEach((t) => {
        if (this.checkboxAnswers.includes(t.code)) {
          t.isRight = true
        } else {
          t.isRight = false
        }
      })
    },
    // 删除多选选项
    deleteCheckboxOption (item) {
      // 记录删除元素是否已找到
      let flag = false
      // 记录删除元素在数组中的索引
      let num = null
      this.addQuestionForm.options.forEach((t, i) => {
        // 判断是不是删除元素后面的元素
        if (flag) {
          // 在删除元素的后面,且答案包含这个字母,就将答案降一个字母
          this.checkboxAnswers.some((t1, i1) => {
            if (t1 === t.code) {
              const newCode = String.fromCharCode(t1.charCodeAt() - 1)
              this.$set(this.checkboxAnswers, i1, newCode)
            }
          })
          // 是后面的元素就将code字母降1级
          t.code = String.fromCharCode(t.code.charCodeAt() - 1)
        }
        // 当找到元素后flag变为true，且记录删除元素的索引
        if (t === item) {
          flag = true
          num = i
          // 如果删除的是选中项,则删除答案数组中对应的数据 (BUG修复)
          if (this.checkboxAnswers.includes(item.code)) {
            this.checkboxAnswers.some((t, i) => {
              if (t === item.code) {
                this.checkboxAnswers.splice(i, 1)
                return true
              }
            })
          }
        }
        // 由于删除元素会导致遍历减少问题，所以放在最后一个元素删除
        if (i === this.addQuestionForm.options.length - 1) {
          this.addQuestionForm.options.splice(num, 1)
        }
      })
    },
    // 添加问题
    OnAddQuestion () {
      this.$refs.addQuestionFormRef.validate(async (isOk) => {
        if (isOk) {
          // 如果题型为简单,则去除optiions里的默认一项
          if (this.addQuestionForm.questionType === '0') {
            this.addQuestionForm.options = []
          }
          // 检测选项是否都以有内容
          if (this.addQuestionForm.options.some((t) => t.title.trim() === '')) {
            return this.$message.error('选项内容不能为空')
          }
          // 检测是否选择正确答案
          if (!this.addQuestionForm.options.some((t) => t.isRight)) {
            return this.$message.error('至少在选项中选择一个正确答案')
          }
          this.addQuestionForm.tags = this.addQuestionForm.tags.join(',')
          try {
            await add(this.addQuestionForm)
            this.$message.success('添加成功')
            this.$router.push('/questions/list')
          } catch (error) {
            this.$message.error('添加失败')
          }
        }
      })
    },
    // 修改问题
    async OnEditQuestion () {
      this.$refs.addQuestionFormRef.validate(async (isOk) => {
        if (isOk) {
          // 如果题型为简单,则去除optiions里的默认一项
          if (this.addQuestionForm.questionType === '0') {
            this.addQuestionForm.options = []
          }
          // 检测选项是否都以有内容
          if (this.addQuestionForm.options.some((t) => t.title.trim() === '')) {
            return this.$message.error('选项内容不能为空')
          }
          // 检测是否选择正确答案
          if (!this.addQuestionForm.options.some((t) => t.isRight)) {
            return this.$message.error('至少在选项中选择一个正确答案')
          }
          if (JSON.stringify(this.addQuestionForm.tags) !== '[]') {
            this.addQuestionForm.tags = this.addQuestionForm.tags.join(',')
          }
          try {
            await update(this.addQuestionForm)
            this.$message.success('修改成功')
            this.$router.push('/questions/list')
          } catch (error) {
            console.error(error)
            this.$message.error('修改失败')
          }
        } else {
          this.$message.error('请填写提示的字段')
        }
      })
    }
  },
  computed: {
    isEdit () {
      return this.$route.query.id
    }
  },
  watch: {
    // 监听学科数据变化，请求对应目录和标签列表
    async 'addQuestionForm.subjectID' (val) {
      if (this.oneEdit) {
        // 选择学科时，重置目录和标签
        this.addQuestionForm.catalogID = null
        this.addQuestionForm.tags = []
        this.directoryList = []
        this.tagList = []
        // 获取当前学科的目录和标签
      }
      this.oneEdit = true
      if (val) {
        // 清空操作时，阻止发送请求
        const directory = await getDirectoryList(val)
        this.directoryList = directory.data
        const results = await getTags(val)
        this.tagList = results.data
      }
    },
    // 监听城市数据变化，获取对应的地区列表
    'addQuestionForm.province' (val) {
      // 选择城市时,清空地区
      if (this.oneEdit1) {
        this.addQuestionForm.city = null
        this.cityList = []
      }
      this.oneEdit1 = true
      // 获取当前城市的地区
      if (val) {
        // 清空操作，就不发送请求
        this.cityList = citys(val)
      }
    },
    // 当题型发生变化,取消对应的配置
    'addQuestionForm.questionType' () {
      // 将options恢复初始
      if (this.oneEdit2) {
        this.addQuestionForm.options = this.$options.data().addQuestionForm.options
        // 将答案置空
        this.radioAnswers = null
        this.checkboxAnswers = []
      }
    }
  }
}
</script>

<style scoped lang='less'>
.el-card {
  margin: 22px;
  padding: 25px 0 50px;
}
/deep/ .el-card__body {
  padding: 0;
}
.line1 {
  margin-top: 20px;
  margin-bottom: 22px;
}
.header {
  padding-left: 25px;
}
.el-form {
  margin: 0 25px;
}
.inputWith {
  width: 450px;
}
/deep/ .city .el-form-item__content {
  margin-left: 0 !important;
}
.el-select {
  width: 100%;
}
.citys {
  margin-left: 5px;
}
/deep/ .option-title .el-input__inner {
  margin-bottom: 2px;
}
.option-row {
  padding-top: 10px;
  margin-bottom: 30px;
}
.option-radio {
  padding-top: 12px;
  margin-right: 5px;
}
.add-option {
  background: #f78989;
  border-color: #f78989;
}
/deep/ .el-upload-dragger {
  width: 100px;
  height: 50px;
  margin-left: 3px;
  margin-top: -8px;
  line-height: 50px;
  overflow: unset;
}
.el-icon-circle-close {
  right: -7px;
  position: absolute;
  top: -8px;
  z-index: 9999;
}
/deep/ .el-checkbox__label {
  margin-right: 4px;
  margin-left: 4px;
}
/deep/ .ql-toolbar {
  height: 35px;
  line-height: 35px;
  padding: 0 !important;
  padding-left: 8px !important;
}
.quill-editor {
  height: 200px;
  margin-bottom: 38px;
}
</style>
